/* eslint-disable no-magic-numbers */
/**
 * @author hanzc (hanzhichen@baijia.com)
 * @date 2021-02-01
 * 正价课学情看板
 */
import React, {useState} from 'react';
import {useMount, useSetState} from 'ahooks';
import moment from 'moment';
import {Row, Col, Card, Typography} from 'antd';
import {
    querySelectOptions,
    queryValues,
    queryDetail,
    download
} from '~/service/refundReport';
import CommonSearchBar from '../../../common/CommonSearchBar';
import DetailCard from '../../../common/DetailCard';
import DetailModal from '../../../common/DetailModal';
import Loading from '../../../common/Loading';
import {
    convertSearcherParams,
    formatRangePickerValue
} from '../../../utils/convert';
import {searchFormPart1} from '../../config';
import CommonTitle from '../../../common/Title';
import GeneralViewBarChart from './GeneralViewBarChart';
import StudioLearningStatusChart from './StudioLearningStatusChart';
import StudioAnswerStatusChart from './StudioAnswerStatusChart';
import HomeWorkChart from './HomeWorkChart';

const {Title} = Typography;

const initialValues = {};
const DashBoardIdPre = 'PriceClass';
const SELECT_UNIT_ID = 'selectUnit_16';

const DashBoardCfg1 = [
    {
        dashBoardName: 'PriceClass_PartOne',
        dashBoardId: 'PriceClass_PartOne'
    },
    {
        dashBoardName: 'PriceClass_PartFour',
        dashBoardId: 'PriceClass_PartFour'
    },
    {
        dashBoardName: 'PriceClass_PartSeven',
        dashBoardId: 'PriceClass_PartSeven'
    },
    {
        dashBoardName: 'PriceClass_PartTen',
        dashBoardId: 'PriceClass_PartTen'
    }
];

const formatDateSearchValue = formatRangePickerValue('YYYY-MM-DD');

/** fineBi经分退费看板part2: 主讲退费情况 */
const LearningStatusDashBoard = () => {
    const [loading, setLoading] = useState(false);
    const [result, setResult] = useSetState({});
    // searchform
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    // detail
    const [detailData, setDetailData] = useState({});
    const [detailModalVisible, setDetailModalVisible] = useState(false);

    // 返回结果是这样的格式
    const {
        PriceClass_PartOne: {
            PriceClass_PartOne_composite_1: generalViewChartUnit = {},
            PriceClass_PartOne_text_1: text1 = {},
            PriceClass_PartOne_text_2: text2 = {},
            PriceClass_PartOne_picture_1: picture1 = {}
        } = {},
        PriceClass_PartFour: {
            PriceClass_PartFour_composite_1: studioLearningStatusChartUnit1 = {}
        } = {},
        PriceClass_PartSeven: {
            PriceClass_PartSeven_composite_1: studioAnswerStatusChartUnit1 = {}
        } = {},
        PriceClass_PartTen: {
            PriceClass_PartTen_composite_1: homeworkChartUnit1 = {}
        } = {}
    } = result;

    /** 查询方法 */
    const getData = (params = {}) => {
        const {
            dashBoardList = [],
            dimensionAndValues = [],
            ...restParams
        } = params;
        setLoading(true);
        Promise.all(
            dashBoardList.map((oneDashBoard = {}) => {
                const {dashBoardId = ''} = oneDashBoard;
                const newDimensionAndValues = dimensionAndValues.map(
                    ({dimensionId: dimId = '', ...restDAV} = {}) => ({
                        dimensionId: `${dashBoardId}_${dimId}`,
                        ...restDAV
                    })
                );
                return queryValues({
                    dashBoardList: [oneDashBoard],
                    dimensionAndValues: newDimensionAndValues,
                    ...restParams
                }).then(res => {
                    const {data = {}} = res;
                    setResult({...data});
                });
            })
        ).finally(() => {
            setLoading(false);
        });
    };

    /** 点击搜索按钮 */
    const handleSearch = params => {
        setSearchFormValues(params);
        const {begin_time: beginTime, ...rest} = params || {};
        let newSearcherParams = params;
        if (beginTime == null) {
            newSearcherParams = rest;
        } else {
            const formattedBeginTime = formatDateSearchValue(beginTime);
            newSearcherParams = {
                // eslint-disable-next-line babel/camelcase
                begin_time: formattedBeginTime,
                ...rest
            };
        }
        const queryParams = {
            dashBoardList: DashBoardCfg1,
            dimensionAndValues: convertSearcherParams(newSearcherParams)
        };
        getData(queryParams);
    };
    const handleReset = () => {
        setSearchFormValues(initialValues);
        const {begin_time: beginTime, ...rest} = initialValues || {};
        let newSearcherParams = initialValues;
        if (beginTime == null) {
            newSearcherParams = rest;
        } else {
            const formattedBeginTime = formatDateSearchValue(beginTime);
            newSearcherParams = {
                // eslint-disable-next-line babel/camelcase
                begin_time: formattedBeginTime,
                ...rest
            };
        }
        const queryParams = {
            dashBoardList: DashBoardCfg1,
            dimensionAndValues: convertSearcherParams(newSearcherParams)
        };
        getData(queryParams);
    };
    // detail
    // 函数柯里化, 提前记录unit参数
    const handleDetail = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        setDetailModalVisible(true);
        // 处理日期
        const {begin_time: beginTime, ...rest} = searchFormValues || {};
        let newSearcherParams = searchFormValues;
        if (beginTime == null) {
            newSearcherParams = rest;
        } else {
            const formattedBeginTime = formatDateSearchValue(beginTime);
            newSearcherParams = {
                // eslint-disable-next-line babel/camelcase
                begin_time: formattedBeginTime,
                ...rest
            };
        }
        // 处理dimensionAndValues, 添加dashBoardId
        const newDimensionAndValues = convertSearcherParams(
            newSearcherParams
        ).map(({dimensionId: dimId = '', ...restDAV} = {}) => ({
            dimensionId: `${dashBoardId}_${dimId}`,
            ...restDAV
        }));
        const params = {
            dimensionAndValues: newDimensionAndValues || [],
            unitId,
            unitName
        };
        queryDetail(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };

    const handleDownload = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        // 处理日期
        const {begin_time: beginTime, ...rest} = searchFormValues || {};
        let newSearcherParams = searchFormValues;
        if (beginTime == null) {
            newSearcherParams = rest;
        } else {
            const formattedBeginTime = formatDateSearchValue(beginTime);
            newSearcherParams = {
                // eslint-disable-next-line babel/camelcase
                begin_time: formattedBeginTime,
                ...rest
            };
        }
        // 处理dimensionAndValues, 添加dashBoardId
        const newDimensionAndValues = convertSearcherParams(
            newSearcherParams
        ).map(({dimensionId: dimId = '', ...restDAV} = {}) => ({
            dimensionId: `${dashBoardId}_${dimId}`,
            ...restDAV
        }));
        const params = {
            dimensionAndValues: newDimensionAndValues || [],
            unitId,
            unitName
        };
        const excelName = unitName ? unitName : null;
        download(params, excelName);
    };
    // 请求单个表单配置项
    const handleFetchOptions = ({
        key,
        searchKey,
        pager,
        dependItemKey,
        dependItemValue,
        isGetingMore,
        options: curOptions,
        fieldsValue
    }) => {
        let permissions = searchFormPart1.map(item => {
            if (item.key === 'begin_time') {
                const [begin, end] = fieldsValue[item.key] || [];
                const filterItems = (begin || end) && [
                    begin && moment(begin).format('YYYY-MM-DD'),
                    end && moment(end).format('YYYY-MM-DD')
                ];
                return {
                    dimensionId: `${DashBoardIdPre}_${item.key}`,
                    dimensionName: item.key,
                    filterItems
                };
            }
            return {
                dimensionId: `${DashBoardIdPre}_${item.key}`,
                dimensionName: item.key,
                filterItems: Array.isArray(fieldsValue[item.key])
                    ? fieldsValue[item.key]
                    : fieldsValue[item.key] == null
                        ? []
                        : [fieldsValue[item.key]]
            };
        });

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: `${DashBoardIdPre}_${key}`,
            dimensionName: key,
            searchKey,
            permissions,
            unitId: SELECT_UNIT_ID
        };

        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    // mount
    useMount(() => {
        const {begin_time: beginTime, ...rest} = initialValues || {};
        let newSearcherParams = initialValues;
        if (beginTime == null) {
            newSearcherParams = rest;
        } else {
            const formattedBeginTime = formatDateSearchValue(beginTime);
            newSearcherParams = {
                // eslint-disable-next-line babel/camelcase
                begin_time: formattedBeginTime,
                ...rest
            };
        }
        const queryParams = {
            dashBoardList: DashBoardCfg1,
            dimensionAndValues: convertSearcherParams(newSearcherParams)
        };
        getData(queryParams);
    }, []);

    return (
        <div>
            <CommonTitle
                type="subTitle"
                title="一、行课历"
                subStyle={{fontSize: 18}}
            />
            <Card style={{width: '100%'}}>
                <div className="profitable-img">
                    <img
                        alt="行课历"
                        width="100%"
                        src={picture1?.pictureUrl ?? ''}
                    />
                </div>
            </Card>
            <CommonTitle
                type="subTitle"
                title="二、正价课数据"
                subStyle={{fontSize: 18}}
            />
            <Card style={{width: '100%', marginBottom: 8}}>
                <CommonSearchBar
                    noCache
                    config={searchFormPart1}
                    selectOptions={selectOptions}
                    initialValues={initialValues}
                    onOk={handleSearch}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    loading={loading}
                />
            </Card>
            <Card>
                <Row wrap>
                    <Col span={24}>
                        <DetailCard
                            title={generalViewChartUnit?.unitName ?? ''}
                            onDownload={handleDownload(
                                generalViewChartUnit,
                                DashBoardCfg1?.[0]?.dashBoardId ?? ''
                            )}
                            onDetail={handleDetail(
                                generalViewChartUnit,
                                DashBoardCfg1?.[0]?.dashBoardId ?? ''
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <GeneralViewBarChart
                                    dataSource={generalViewChartUnit}
                                    id="GeneralViewBarChart"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={24}>
                        <DetailCard
                            title={studioLearningStatusChartUnit1?.unitName ?? ''}
                            onDownload={handleDownload(
                                studioLearningStatusChartUnit1,
                                DashBoardCfg1?.[1]?.dashBoardId ?? ''
                            )}
                            onDetail={handleDetail(
                                studioLearningStatusChartUnit1,
                                DashBoardCfg1?.[1]?.dashBoardId ?? ''
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <StudioLearningStatusChart
                                    dataSource={studioLearningStatusChartUnit1}
                                    id="StudioLearningStatusChart1"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={24}>
                        <DetailCard
                            title={studioAnswerStatusChartUnit1?.unitName ?? ''}
                            onDownload={handleDownload(
                                studioAnswerStatusChartUnit1,
                                DashBoardCfg1?.[4]?.dashBoardId ?? ''
                            )}
                            onDetail={handleDetail(
                                studioAnswerStatusChartUnit1,
                                DashBoardCfg1?.[4]?.dashBoardId ?? ''
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <StudioAnswerStatusChart
                                    dataSource={studioAnswerStatusChartUnit1}
                                    id="StudioAnswerStatusChart1"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={24}>
                        <DetailCard
                            title={homeworkChartUnit1?.unitName ?? ''}
                            onDownload={handleDownload(
                                homeworkChartUnit1,
                                DashBoardCfg1?.[7]?.dashBoardId ?? ''
                            )}
                            onDetail={handleDetail(
                                homeworkChartUnit1,
                                DashBoardCfg1?.[7]?.dashBoardId ?? ''
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <HomeWorkChart
                                    dataSource={homeworkChartUnit1}
                                    id="HomeWorkChart1"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
            </Card>
            <DetailModal
                data={detailData}
                detailModalVisible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
            />
        </div>
    );
};

export default LearningStatusDashBoard;
